package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Utility class extract zip files.
 * 
 * @author sheryl.tay.2012, jaslin.wee.2012
 * 
 */
public class UnzipUtil {

	/**
	 * Extracts the zip file in the given path to the given output directory.
	 * Overwrites files with same file name.
	 * 
	 * @param zipFilePath
	 * @param outputDirectoryPath
	 */
	public static void extractZipFile(String zipFilePath,
			String outputDirectoryPath) {

		byte[] buffer = new byte[1024];

		try {

			// create output directory if it doesn't exists
			createNonExistingDirectory(outputDirectoryPath);

			// get the zip file content
			ZipInputStream zipInputStream = new ZipInputStream(
					new FileInputStream(zipFilePath));

			// get the zipped file list entry
			ZipEntry zipEntry = null;
			while ((zipEntry = zipInputStream.getNextEntry()) != null) {

				String fileName = zipEntry.getName();
				File newFile = new File(outputDirectoryPath + File.separator
						+ fileName);

				// create all non existing directories
				createNonExistingDirectory(newFile.getParent());

				// write file
				FileOutputStream fileOutputStream = new FileOutputStream(
						newFile);
				int len = 0;
				while ((len = zipInputStream.read(buffer)) > 0) {
					fileOutputStream.write(buffer, 0, len);
				}

				fileOutputStream.close();
			}

			zipInputStream.closeEntry();
			zipInputStream.close();

		} catch (IOException ex) {
			Logger.getLogger(UnzipUtil.class.getName()).log(Level.SEVERE,
					"IOException: " + zipFilePath, ex);
			ex.printStackTrace();
		}
	}

	/**
	 * Creates directory if it does not already exists.
	 * 
	 * @param directoryPath
	 */
	private static void createNonExistingDirectory(String directoryPath) {
		File dir = new File(directoryPath);
		if (!dir.exists()) {
			dir.mkdir();
		}
	}

}
